import time

from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from tools.myjwt import mjwt



class PermissionMiddleware(MiddlewareMixin):
    def process_request(self, request):
       
        #定义白名单
        wlist = ["/login/",'/register/','/sendmobile/']
        #判断当前请求的url是否在白名单中
      
        #如果不在，获取token
        if request.path not in wlist:
            try:
                token = request.headers.get('Authorzation')
                #解析token
                data = mjwt.jwt_decode(token)
                # 获取用户id
                userid = data['userid']
                request.userid = userid
                print(data)
                if int(time.time()) > int(data['exp']):
                    return JsonResponse({"code":401,'mes':'token过期'})
            except:
                return JsonResponse({"code":401,'mes':'没获取token无权操作'})
            
            
       
       
        #是否被修改，是否过期

        # wlist = ['/user/' + i for i in
        #          ['imagecode/', 'messagecode/', 'register/', 'login/', 'dingtalklogin/', 'dingtalkCallback/',
        #           'token/']] + ["/shopping/comment/", "/es/", "/tinymce/"]
        # path = request.path
        # method = request.method
        # # 过滤不需要登录的接口
        # if path not in wlist:
        #     token = request.headers.get('Authorization')
        #     if not token:
        #         return JsonResponse({"code": 20001, "msg": "token不存在"})
        #     if r.get_str(token):
        #         return JsonResponse({"code": 20002, "msg": "用户已退出，请重新登录"})
        #     payload = myjwt.jwt_decode(token)
        #     if not payload:
        #         return JsonResponse({"code": 20003, "msg": "token错误"})
        #     if int(time.time()) > payload["exp"]:
        #         return JsonResponse({"code": 20004, "msg": "token已过期"})
        #     request.userid = payload["userid"]
